const app = getApp();
import request from '../../utils/http.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectIndex: 0, //1分享登录  2 下单登录 3加入购物车登录
    left: 0,
    title: ["服务内容"],
    currentTab: 0,

    scrollFlag: false,
    phone: '',
    personId: 0,
    dianPuDengJi: 6,
    IsLogin: false,
    userInfo: {},
    hasUserInfo: false,
    // hiddenPopPaper: false, //微信授权

    winHeight: 0,
    width: 0,
    screenHeight: 0,
    touXiangUrl: '',
    niCheng: '',
    tjr_id: 0,
    dianPuId: 0, //当前店铺ID
    login_dianPuId: 0,


    productId: 0, //产品id
    chanPinMingCheng: '', //产品名称
    tuPianUrl: '', //产品封面
    xianShiJiaGe: 0, //原价
    shiJiJiaGe: 0, //实际销售价格
    huiYuanJiaGe: 0, //会员价格
    guiGe: '', //显示规格


    yunFeiTxt: '',
    faHuoZhouQiShuoMing: '',
    chanPinShuoMing: '', //说明

    fuKuanRenShu: 0, //显示销售数量
    kuCun: 0, //库存
    jingXuanZhuangTai: 1,
    reXiaoZhuangTai: 1,


    chanPinImageList: [],
    shiPinUrl: "",
    swiperListLength: 1,
    index: 1, //当前图片位置
    neiRong: '', //产品详情



    syHtml: '', //服务包扩展1 适用范围
    ysHtml: '', //服务包扩展2 医生团队
    fwHtml: '', //服务包扩展3 服务优势
    zzHtml: '', //服务包扩展4 增值服务
    CertifiCardLength: 0,
    CertifiCardList: [], //营业执照


    gouWuCheCount: 0, //购物车商品数量
    goumaiCount: 1, //直接购买产品数量
    qiGouShuLiang: 1, //最小起购数量



    gouMaible: false, //立即购买弹框
    shareble: false, //分享弹框
    raiseble: false, //众筹弹框
    increase: false, //服务对象信息添加
    hiddenSharePaper: true, //分享海报的弹框是否隐藏

    bottomViewble: false, //底部固定栏是否隐藏

    scrollTop: 0, //页面滚动位置
    opacity: 0, //根据页面滚动位置，显示头部信息透明度

    shareFlag: false, //true 通过分享进入产品页面，需跳转店铺首页

    code: '',


    canvas: {},
    canvasWidth: 0,
    renderHeight: 0,
    canvasdestWidth: 0,
    canvasdestHeight: 0,



    zs_productId: 0,

    guid_short: 0,
    zslist: [],
    zslistLength: 0,
    keGouMaiShouLiang: 1, //可购买数量


    yiShengList: [],
    yiShengListlength: 0,
    guidList: [], //会员开通人
    guidListLength: 0,
    guid: '',
    shopBuyerGuid: '',
    guidname: '',
    shangJiaStatus: 1, //是否上架: 1是 2否
    MenuButtonTop: 50,
    MenuButtonHeight: 30,
    CustomBar: 60,

    zhongXinChanPinList: [],
    xianXiaXiangMuList: [],
    qianYuePdf: '',
    isRead: false, //是否同意服务条款


    userName: '', //联系人
    provinceName: '', //省
    cityName: '',
    countyName: '', //区
    detailInfo: '', //详细地址
    telNumber: '', //联系电话
    postalCode: '',
    nationalCode: '',

    zhongChouZhuangTai: '', //众筹状态

    jzrname: '', //就诊人姓名
    jzrsfz: '', //就诊人身份证号
    jzrphone: '', //就诊人手机号

    yjyToken: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this

    wx.login({
      success: res => {
        that.setData({
          code: res.code
        })
      }
    })

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          screenHeight: res.screenHeight,
          width: res.screenWidth,
          winHeight: res.windowHeight - (460 / 750 * res.windowWidth),
        })
      }
    })


    that.setData({
      login_dianPuId: (wx.getStorageSync(app.globalData.SHOPID) == '' || wx.getStorageSync(app.globalData.SHOPID) == undefined) ? 1 : wx.getStorageSync(app.globalData.SHOPID),
      CustomBar: app.globalData.CustomBar,
      MenuButtonTop: app.globalData.MenuButtonTop,
      MenuButtonHeight: app.globalData.MenuButtonHeight,
      productId: options.productId,
      personId: wx.getStorageSync(app.globalData.PERSON_ID),
      phone: wx.getStorageSync(app.globalData.PHONENUMBER),

      dianPuId: (options.dianPuId == '' || options.dianPuId == undefined) ? ((wx.getStorageSync(app.globalData.SHOPID) == '' || wx.getStorageSync(app.globalData.SHOPID) == undefined) ? 1 : wx.getStorageSync(app.globalData.SHOPID)) : options.dianPuId,
      tjr_id: (options.tjr_id == '' || options.tjr_id == undefined) ? wx.getStorageSync(app.globalData.TJR_ID) : options.tjr_id,
      touXiangUrl: wx.getStorageSync(app.globalData.TouXiang),
      niCheng: wx.getStorageSync(app.globalData.NiCheng),
      shareFlag: (options.tjr_id == '' || options.tjr_id == undefined) ? false : true,

      userName: wx.getStorageSync(app.globalData.USERNAME), //联系人
      provinceName: wx.getStorageSync(app.globalData.PROVINCENAME), //省
      cityName: wx.getStorageSync(app.globalData.CITYNAME),
      countyName: wx.getStorageSync(app.globalData.COUNTYNAME), //区
      detailInfo: wx.getStorageSync(app.globalData.DETAILINFO), //详细地址
      telNumber: wx.getStorageSync(app.globalData.TELNUMBER), //联系电话
    })

    if (options.scene) { //海报扫码
      let scene = decodeURIComponent(options.scene);
      that.setData({
        dianPuId: scene.split("_")[0],
        tjr_id: scene.split("_")[1],
        productId: scene.split("_")[2],
        guid_short: scene.split("_")[3] == '' || scene.split("_")[3] == null ? 0 : scene.split("_")[3],
        shareFlag: true
      })
    }

    wx.setStorageSync(app.globalData.SHOPID, that.data.dianPuId)
    wx.setStorageSync(app.globalData.TJR_ID, that.data.tjr_id)
    // wx.setStorageSync(app.globalData.LOGINSTATUS, that.data.IsLogin)
    if (that.data.login_dianPuId == that.data.dianPuId && that.data.dianPuId > 0) {
      that.setData({
        IsLogin: wx.getStorageSync(app.globalData.LOGINSTATUS) == true ? true : false,
      })

    } else {
      that.setData({
        IsLogin: false,
      })
    }

    wx.setStorageSync(app.globalData.LOGINSTATUS, that.data.IsLogin)
    that.getProductDetail();
    that.getToken_YJY()

  },



  //获取产品详情
  getProductDetail: function () {
    var that = this
    wx.showLoading({
      title: '加载中...',
      mask: true
    })
    let data = {
      fuWuBaoChanPinIdId: that.data.productId,

    }
    request.get('fuWuBao/fuWuBaoDetailInfo', data, res => {
      // console.log("服务包:" +  JSON.stringify(res.data))
      wx.hideLoading();
      that.setData({
        chanPinMingCheng: res.data.mingCheng,
        tuPianUrl: res.data.productBeiJingTuUrl,
        xianShiJiaGe: res.data.xianShiJiaGe,
        shiJiJiaGe: res.data.tongYiJiaGe,
        huiYuanJiaGe: res.data.huiYuanJiaGe,
        kuCun: 999,
        fuKuanRenShu: res.data.xuNiXiaoLiang,
        guiGe: '套',
        faHuoZhouQiShuoMing: res.data.faHuoZhouQiShuoMing,
        chanPinShuoMing: res.data.productComment,

        yunFeiTxt: '包邮',
        shiPinUrl: res.data.shiPinUrl,
        chanPinImageList: res.data.chanPinImageList,
        swiperListLength: res.data.shiPinUrl == '' ? res.data.chanPinImageList.length : parseInt(res.data.chanPinImageList.length + 1),
        gouWuCheCount: 0,
        goumaiCount: 1,
        qiGouShuLiang: 1,
        yiShengList: res.data.yiShengList,
        yiShengListlength: res.data.yiShengList.length,
        shangJiaStatus: res.data.shangJiaStatus,
        zhongXinChanPinList: res.data.zhongXinChanPinList,
        xianXiaXiangMuList: res.data.xianXiaXiangMuList,
        qianYuePdf: res.data.qianYuePdf,
        zhongChouZhuangTai: res.data.zhongChouZhuangTai, //众筹状态
      })
      var html = res.data.productInfo.replace(/<img /g, "<img style='max-width:100%;height:auto;display:block;'")
      var htmlS = html.replace(/style=""/g, '')

      that.setData({
        neiRong: htmlS
      })

      if (res.data.xianXiaXiangMuList.length > 0) {
        that.data.title.push("服务项目")
        that.setData({
          title: that.data.title
        })
      }

      if (res.data.zhongXinChanPinList.length > 0) {
        that.data.title.push("产品组合")
        that.setData({
          title: that.data.title
        })
      }

      // syHtml:'',//服务包扩展1 适用范围
      // ysHtml:'',//服务包扩展2 医生团队
      // fwHtml:'',//服务包扩展3 服务优势
      // zzHtml:'',//服务包扩展4 增值服务


      if (res.data.text1 != '') {
        var html = res.data.text1.replace(/<img /g, "<img style='max-width:100%;height:auto;display:block;'")
        var htmlS = html.replace(/style=""/g, '')
        that.data.title.push("适用范围")
        that.setData({
          syHtml: htmlS,
          title: that.data.title
        })
      }


      if (res.data.text2 != '') {
        var html = res.data.text2.replace(/<img /g, "<img style='max-width:100%;height:auto;display:block;'")
        var htmlS = html.replace(/style=""/g, '')
        that.data.title.push("医生团队")
        that.setData({
          ysHtml: htmlS,
          title: that.data.title
        })
      }

      if (res.data.text3 != '') {
        var html = res.data.text3.replace(/<img /g, "<img style='max-width:100%;height:auto;display:block;'")
        var htmlS = html.replace(/style=""/g, '')
        that.data.title.push("服务优势")
        that.setData({
          fwHtml: htmlS,
          title: that.data.title
        })
      }

      if (res.data.text4 != '') {
        var html = res.data.text4.replace(/<img /g, "<img style='max-width:100%;height:auto;display:block;'")
        var htmlS = html.replace(/style=""/g, '')
        that.data.title.push("增值服务")
        that.setData({
          zzHtml: htmlS,
          title: that.data.title
        })
      }

      that.getCertifiCard(); //查询营业执照
      that.getZengPinList()

      //以下废除
      // if (that.data.guid_short > 0) { //机器端分享过来，代替支付的
      //   that.getJZpersonOne(that.data.guid_short)
      // }

      // if (that.data.guid_short == 0 && that.data.IsLogin) { //是会员卡，且没有带具体guid
      //   that.getJZPersonList(); //获取所有就诊人
      // }


    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '查询失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })

  },


  getCertifiCard: function () {
    var that = this

    let data = {
      fuWuBaoChanPinId: that.data.productId,

    }
    request.get('fuWuBao/getProductGongYingShangZiZhi', data, res => {

      // console.log("营业执照:" + JSON.stringify(res.data))

      if (res.data.length > 0) {
        that.data.title.push("供应商")
        that.setData({
          title: that.data.title,
          CertifiCardList: res.data
        })
      }


    }, err => {

      wx.showToast({
        title: '查询失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })
  },

  //获取一个产品的赠送产品
  getZengPinList: function () {
    var that = this
    let data = {
      fuWuBaoChanPinIdId: that.data.productId,
    }

    request.get('fuWuBao/fuWuBaoZengPin', data, res => {
      // console.log("赠送产品:" + JSON.stringify(res.data))
      that.setData({
        zslist: res.data.zhongXinChanPinList, //赠送商品列表  
        zslistLength: res.data.zhongXinChanPinList == null ? 0 : res.data.zhongXinChanPinList.length,
        zs_productId: (res.data.zhongXinChanPinList.length > 0) ? res.data.zhongXinChanPinList[0].productId : 0, //默认赠品ID
      })

      wx.hideLoading();
    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '获取信息失败', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })
  },


  //获取医加医外部token
  getToken_YJY: function () {
    var that = this;
    wx.request({
      url: app.globalData.base_yjy_url + 'lo/GetToken',
      method: 'POST',
      data: {
        id: '11001002',
        password: '763986',
      },
      success: function (res) {
        // console.log("获取医加医token:" + JSON.stringify(res))
        if (res.data.code == 1) {
          that.setData({
            yjyToken: res.data.data.token
          })

          if (that.data.guid_short > 0) {
            that.getJZR_YJY('', that.data.guid_short)
          } else if (that.data.phone != '') {
            that.getJZR_YJY(that.data.phone, '')
          }

        } else {
          wx.showToast({
            title: '获取token失败', // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })
        }

      },
      fail: function (err) {

        wx.showToast({
          title: '获取token失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {

      }
    })
  },


  //根据手机号，或者短GUId，获取就诊人list
  getJZR_YJY: function (phone, guid_short) {
    var that = this;
    wx.request({
      url: app.globalData.base_yjy_url + 'robot/queryBuyer',
      method: 'POST',
      header: {
        'token': that.data.yjyToken,
      },
      data: {
        phone: phone,
        patientId: guid_short,
      },
      success: function (res) {
        console.log("就诊人:" + JSON.stringify(res))
        if (res.data.code == 1) {
          that.setData({
            guidList: res.data.data,
            guidListLength: res.data.data == null ? 0 : res.data.data.length,
          })
        }

      },
      fail: function (err) {

        wx.showToast({
          title: '获取就诊人失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {

      }
    })
  },

  //添加就诊人
  addJZR_YJY: function () {
    var that = this;
    wx.showLoading({
      title: '处理中...',
      mask: true
    })
    wx.request({
      url: app.globalData.base_yjy_url + 'robot/newBuyer',
      method: 'POST',
      header: {
        'token': that.data.yjyToken,
      },
      data: {
        name: that.data.jzrname,
        idcard: that.data.jzrsfz,
        patientPhone: that.data.jzrphone,
        buyPhone: that.data.phone,
        shopid: that.data.dianPuId

      },
      success: function (res) {
        console.log("添加就诊人:" + JSON.stringify(res))
        if (res.data.code == 1) {
          that.getJZR_YJY(that.data.phone, '')
          that.setData({
            jzrname: '',
            jzrsfz: '',
            jzrphone: '',

            gouMaible: true,
            bottomViewble: false,
            increase: false,
          })
        } else {
          var mess = res.data.message
          wx.showToast({
            title: mess, // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })
        }
        wx.hideLoading();

      },
      fail: function (err) {
        wx.hideLoading();
        wx.showToast({
          title: '添加就诊人失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {

      }
    })
  },


  //会员绑定
  radioChange(e) {
    console.log('绑定会员id：', e.detail.value)
    this.setData({
      guid: this.data.guidList[e.detail.value].patient_unique_guid,
      guidname: this.data.guidList[e.detail.value].name,
      shopBuyerGuid: this.data.guidList[e.detail.value].shopBuyerGuid,
    })
  },


  //点击显示弹框
  pickShare() {
    if (this.data.IsLogin) {
      this.setData({
        shareble: true,
        bottomViewble: true,
      })
    } else {
      wx.showToast({
        title: '请先登录', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })

    }
  },

  //点击显示添加服务对象信息弹框
  increase() {
    this.setData({
      increase: true,
      bottomViewble: true,
      gouMaible: false,
    })
  },

  //点击关闭添加服务对象信息弹框
  increasefalse() {
    this.setData({
      increase: false,
      bottomViewble: false,
      // isRead: false,
      gouMaible: true
    })
  },

  pop_up: function () {
    var that = this;
    // 验证姓名是否为空
    if (that.data.jzrname === '') {
      wx.showToast({
        title: '姓名不能为空!!!',
        icon: "none",
        duration: 2000,
        mask: false,
      });
      return; // 如果姓名为空，则不再继续后续验证和操作
    }
    // 验证身份证号是否为空及长度是否为18位
    if (!that.data.jzrsfz || that.data.jzrsfz.length !== 18) {
      let errMsg = that.data.jzrsfz ? '请输入正确的身份证号' : '身份证号不能为空';
      wx.showToast({
        title: errMsg,
        icon: "none",
        duration: 2000,
        mask: false,
      });
      return;
    }

    if (!that.data.jzrphone || that.data.jzrphone.length !== 11) {
      let errMsg = that.data.jzrphone ? '请输入正确的手机号' : '手机号不能为空';
      wx.showToast({
        title: errMsg,
        icon: "none",
        duration: 2000,
        mask: false,
      });
      return;
    }
    // 身份证号验证通过后，显示确认提交模态框
    wx.showModal({
      title: '提交确认',
      content: '是否确定提交',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确定',
      success: function (res) {
        if (res.confirm) {
          that.setData({

          });
          that.addJZR_YJY();
        } else if (res.cancel) {
          that.increasefalse();
          return;
        }
      },
    });
  },


  // 关闭弹框
  citySure(e) {
    this.setData({
      bottomViewble: false,
    })
  },


  //提示同意服务条款
  agreedToast() {
    wx.showToast({
      title: '需先同意服务条款', // 提示的内容
      icon: "none", // 图标，默认success
      duration: 2000, // 提示的延迟时间，默认1500
      mask: false, // 是否显示透明蒙层，防止触摸穿透
    })
  },

  //同意服务条款
  changeCheck() {
    this.setData({
      isRead: !this.data.isRead,
    });
  },

  //服务条款详情
  toserveInfo() {
    // wx.navigateTo({
    //   url:'/pkg_index/pages/xieyi_FWB/xieyi_FWB' ,
    // })
    var that = this
    if (that.data.qianYuePdf != '') {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })

      wx.downloadFile({
        // 示例 url，并非真实存在
        url: that.data.qianYuePdf,
        success: function (res) {
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
          wx.hideLoading();
        }
      })

    } else {
      wx.showToast({
        title: '详细协议，请咨询客服', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 4000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }



  },

  // 关闭分享弹框
  colseShare: function () {
    this.setData({
      shareble: false,
      bottomViewble: false,

    })
  },

  //购买
  gouMaibind: function (e) {
    var that = this
    if (that.data.IsLogin) { //登录了
      if (that.data.gouMaible) { //第二次点立即购买
        // if ((that.data.guid == 0 || that.data.guid == '')) {
        //   wx.showToast({
        //     title: '请选择服务对象(如未显示，请先添加健康档案)', // 提示的内容
        //     icon: "none", // 图标，默认success
        //     duration: 4000, // 提示的延迟时间，默认1500
        //     mask: false, // 是否显示透明蒙层，防止触摸穿透
        //   })

        // } else {
          that.setData({
            gouMaible: !that.data.gouMaible
          })
          wx.navigateTo({
            url: '/pages/orders_querenFWB/orders_querenFWB?productId=' + that.data.productId + '&goumaiCount=' + that.data.goumaiCount + '&zengSongChanPinId=' + that.data.zs_productId + '&guid=' + that.data.guid + '&name=' + that.data.guidname + '&shopBuyerGuid=' + this.data.shopBuyerGuid,
          })
        // }


      } else { //第一次点立即购买
        that.setData({
          gouMaible: !that.data.gouMaible
        })
      }
    } else { //未登录，添加到临时全局gwcList
      that.setData({
        selectIndex: 2
      })
      that.toLogin()
    }
  },

  //关闭购买数量设置
  closeGoumai(e) {
    this.setData({
      gouMaible: false,
      raiseble: false,
      bottomViewble: false
    })
  },

  //获取滚动条位置，当到固定值时，固定店铺信息和菜单栏
  onPageScroll: function (e) {
    this.setData({
      scrollTop: e.scrollTop,
      opacity: e.scrollTop / this.data.width > 1 ? 1 : e.scrollTop / this.data.width
    })
  },


  //直接购买——添加数量
  bindAddTap: function () {

    if (this.data.goumaiCount < this.data.keGouMaiShouLiang) {
      this.setData({
        goumaiCount: this.data.goumaiCount + 1
      })
    } else {
      wx.showToast({
        title: '超出当前产品最大购买数量', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }


  },

  //直接购买——减少数量
  bindReduceTap: function () {
    if (this.data.goumaiCount > this.data.qiGouShuLiang) {
      this.setData({
        goumaiCount: this.data.goumaiCount - 1
      })
    }
  },

  //服务包发起数量
  raiseCount: function () {
    wx.showToast({
      title: '服务包能且只能众筹1件', // 提示的内容
      icon: "none", // 图标，默认success
      duration: 1000, // 提示的延迟时间，默认1500
      mask: false, // 是否显示透明蒙层，防止触摸穿透
    })
  },

  //轮播图index
  currentAction: function (e) {
    // console.log(e.detail.current)
    this.setData({
      index: e.detail.current + 1
    })
  },

  //产品分组切换

  onTabsChange(e) {
    // console.log("value:" + e.detail.value)
    this.setData({
      currentTab: e.detail.value
    })
  },

  // 点击标题切换当前页时改变样式
  swichNav: function (e) {
    //  console.log("节点:" + JSON.stringify(e))

    let index = e.detail.current
    //  console.log("current:" + index)
    if (this.data.currentTab == index) {
      return false;
    } else {
      this.setData({
        currentTab: index
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取swipre高度，设置店铺信息和菜单固定位置

    if (this.data.IsLogin) {
      wx.showShareMenu({
        menus: ['shareAppMessage', 'shareTimeline']
      })

    } else {
      wx.hideShareMenu({
        menus: ['shareAppMessage', 'shareTimeline']
      })
    }

    // this.getProductDetail(); // 刷新购物车
  },


  //返回
  bindNavigateBack: function () {
    if (this.data.shareFlag == true) {
      wx.switchTab({
        url: '/pages/shop/shop',
      })
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },


  //阶段伸展效果
  szAction: function (e) {
    var index = e.currentTarget.dataset.index;

    this.data.xianXiaXiangMuList[index].isSZ = !this.data.xianXiaXiangMuList[index].isSZ
    this.setData({
      xianXiaXiangMuList: this.data.xianXiaXiangMuList
    })

    // console.log(index)
  },


  //跳转首页
  bindToIndex: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })

  },


  //分享产品
  onShareAppMessage: function (res) {
    var that = this;
    that.setData({
      shareble: false
    })

    if (that.data.IsLogin) {
      return {
        title: that.data.chanPinMingCheng,
        path: '/pages/productInfo_FWB/productInfo_FWB?dianPuId=' + that.data.dianPuId + '&&productId=' + that.data.productId + '&&tjr_id=' + that.data.personId,
        imageUrl: that.data.tuPianUrl
      }
    } else {
      wx.showToast({
        title: '请先登录！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }
  },


  //海报关闭
  bindClosePaper: function () {
    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper,
      bottomViewble: !this.data.bottomViewble
    })
  },

  //产品生成海报
  bindProTap: function (e) {
    wx.showLoading({
      title: '海报生成中...',
    })
    var that = this
    that.setData({
      shareble: false
    })
    that.getWechatCode(that.data.tuPianUrl);
  },

  //获取微信二维码(用于链接)
  getWechatCode: function (paperUrl) {
    var that = this
    var sceneStr = that.data.dianPuId + '_' + that.data.personId + '_' + that.data.productId + '_0'
    //console.log("sceneStr：" + sceneStr)
    wx.request({
      url: app.globalData.base_url + 'resource/getQRAndUpToQiNiu',
      data: {
        // id: that.data.productId,
        dianPuId: that.data.dianPuId,
        leiXing: 2, //1人的二维码，2产品的二维码
        path: "pages/productInfo_FWB/productInfo_FWB",
        scene: sceneStr
      },
      success: function (res) {
        console.log("wxerWeiMaUrl:" + JSON.stringify(res.data))
        var wxerWeiMaUrl = res.data.WXErWeiMaUrl;
        that.createProImg(paperUrl, wxerWeiMaUrl, that.data.touXiangUrl);
      }
    })
  },


  //绘制海报
  createProImg: function (paperUrl, wxerWeiMaUrl, touXiangUrl) {
    this.setData({
      hiddenSharePaper: !this.data.hiddenSharePaper
    })

    wx.hideLoading();
    wx.createSelectorQuery()
      .select('#myCanvas') // 在 WXML 中填入的 id
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {

        // console.log("画图:" + JSON.stringify(res))

        const canvas = res[0].node
        // Canvas 画布的实际绘制宽高
        const renderWidth = res[0].width
        const renderHeight = res[0].height
        // console.log(renderWidth)
        // Canvas 绘制上下文
        const ctx = canvas.getContext('2d')

        // 初始化画布大小
        const dpr = wx.getWindowInfo().pixelRatio
        // console.log("dpr:" + dpr)
        canvas.width = renderWidth * dpr
        canvas.height = renderHeight * dpr

        var scale = (renderWidth / 580) * dpr;

        this.setData({
          canvas: canvas,
          canvasWidth: renderWidth,
          renderHeight: renderHeight,
          canvasdestWidth: renderWidth * dpr,
          canvasdestHeight: renderHeight * dpr,
        })

        // ctx.scale(dpr, dpr)

        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, 580 * scale, 920 * scale);



        ctx.beginPath();
        ctx.lineWidth = "1";
        ctx.strokeStyle = "rgb(220,220,220)"; // Green path
        ctx.moveTo(0, 760 * scale);
        ctx.lineTo(580 * scale, 760 * scale);
        ctx.stroke(); // Draw it

        //画主图      
        const imageMain = canvas.createImage();
        imageMain.src = paperUrl;
        imageMain.onload = () => {
          ctx.drawImage(imageMain, 10 * scale, 10 * scale, 560 * scale, 560 * scale)

        }

        var priceIconSize = 28 * scale
        var priceIconSizestr = priceIconSize + 'px Arial'

        //价格

        let shiJiJiaGeICON = {
          x: 16 * scale,
          y: 610 * scale,
          color: '#f92b3a',
          size: priceIconSizestr,
          align: 'left',
          baseline: 'top',
          text: '￥',
          bold: false
        };
        this.drawText(ctx, shiJiJiaGeICON);


        var priceSize = 40 * scale
        var priceSizestr = priceSize + 'px Arial'

        let shiJiJiaGe = {
          x: 50 * scale,
          y: 600 * scale,
          color: '#f92b3a',
          size: priceSizestr,
          align: 'left',
          baseline: 'top',
          text: this.data.shiJiJiaGe / 100,
          bold: true
        };
        this.drawText(ctx, shiJiJiaGe);

        //产品名称
        var productNameSize = 30 * scale
        var productNameSizestr = productNameSize + 'px Arial'

        if (this.data.chanPinMingCheng.length > 40) {
          var proName1 = this.data.chanPinMingCheng.substring(0, 20)


          let proName1Cont = {
            x: 16 * scale,
            y: 660 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName1,
            bold: false
          };
          this.drawText(ctx, proName1Cont);


          var proName2 = this.data.chanPinMingCheng.substring(20, 40) + '...'

          let proName2Cont = {
            x: 16 * scale,
            y: 700 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName2,
            bold: false
          };
          this.drawText(ctx, proName2Cont);

        } else if (this.data.chanPinMingCheng.length < 40 && this.data.chanPinMingCheng.length > 20) {
          var proName1 = this.data.chanPinMingCheng.substring(0, 20)
          let proName1Cont = {
            x: 16 * scale,
            y: 660 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName1,
            bold: false
          };
          this.drawText(ctx, proName1Cont);

          var proName2 = this.data.chanPinMingCheng.substring(20, this.data.chanPinMingCheng.length)
          let proName2Cont = {
            x: 16 * scale,
            y: 704 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: proName2,
            bold: false
          };
          this.drawText(ctx, proName2Cont);

        } else {
          //画产品名称
          let chanPinMingCheng = {
            x: 16 * scale,
            y: 660 * scale,
            color: '#474646',
            size: productNameSizestr,
            align: 'left',
            baseline: 'top',
            text: this.data.chanPinMingCheng,
            bold: false
          };
          this.drawText(ctx, chanPinMingCheng);
        }



        ctx.save()
        //画二维码        
        const imageCode = canvas.createImage();
        imageCode.src = wxerWeiMaUrl;
        imageCode.onload = () => {
          ctx.drawImage(imageCode, 400 * scale, 770 * scale, 140 * scale, 140 * scale)

        }



        //画推荐人头像      
        const imageTouX = canvas.createImage();
        imageTouX.src = touXiangUrl;
        imageTouX.onload = () => {
          // 将图片绘制到 canvas 上
          ctx.save()
          ctx.beginPath(); //开始绘制
          // ctx.strokeStyle="white"
          ctx.arc(80 * scale, 840 * scale, 50 * scale, 0, Math.PI * 2, false);
          // ctx.stroke();
          ctx.clip(); //画了圆 再剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内
          ctx.drawImage(imageTouX, 30 * scale, 790 * scale, 100 * scale, 100 * scale)
          ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 可以继续绘制

        }

        var tjrNameSize = 28 * scale
        var tjrNameSizestr = tjrNameSize + 'px Arial'

        //推荐人昵称
        let userName = {
          x: 144 * scale,
          y: 838 * scale,
          color: '#838080',
          size: tjrNameSizestr,
          align: 'left',
          baseline: 'bottom',
          text: this.data.niCheng,
          bold: false
        };
        this.drawText(ctx, userName);

        //推荐说明
        var tjrSMSize = 20 * scale
        var tjrSMSizestr = tjrSMSize + 'px Arial'

        let tjContent = {
          x: 144 * scale,
          y: 850 * scale,
          color: '#b3b3b3',
          size: tjrSMSizestr,
          align: 'left',
          baseline: 'top',
          text: '为您推荐',
          bold: false
        };
        this.drawText(ctx, tjContent);


      })



  },


  drawText: function (ctx, obj) {
    ctx.save();
    ctx.fillStyle = obj.color;
    // ctx.setFontSize(obj.size);
    ctx.font = obj.size;
    // ctx.setTextAlign(obj.align);
    ctx.textAlign = obj.align;
    // ctx.setTextBaseline(obj.baseline);
    ctx.textBaseline = obj.baseline;

    // ctx.font="20px Georgia";
    // ctx.fillText(obj.text, obj.x,obj.y);

    if (obj.bold) {
      ctx.fillText(obj.text, obj.x, obj.y - 0.5);
      ctx.fillText(obj.text, obj.x - 0.5, obj.y);
    }
    ctx.fillText(obj.text, obj.x, obj.y);
    if (obj.bold) {
      ctx.fillText(obj.text, obj.x, obj.y + 0.5);
      ctx.fillText(obj.text, obj.x + 0.5, obj.y);
    }
    ctx.restore();
  },


  //保存图片权限判断
  isgetPower: function () {

    var that = this
    wx.getSetting({
      success(res) {
        if (['scope.writePhotosAlbum'] in res.authSetting) {
          // 如果授权过且同意了
          if (res.authSetting[`scope.writePhotosAlbum`]) {
            that.bindSavePaper()
          } else {
            wx.showModal({
              title: "请求授权相册存储",
              content: "需要获取您的相册存储权限，请确认授权",
              success: res => {
                if (res.confirm) {
                  wx.openSetting({
                    success: res => {
                      that.bindSavePaper()
                      console.log(res)
                    },
                    fail: err => {
                      console.log(err)
                    }
                  })
                } else if (res.cancel) {
                  console.log("你又取消了")
                }
              }
            })
          }
        } else {
          that.bindSavePaper()
        }
      }
    })




  },

  //保存图片到相册
  bindSavePaper: function () {
    wx.showLoading({
      title: '生成中...',
    })

    // var that = this

    wx.canvasToTempFilePath({
      canvas: this.data.canvas,
      x: 0,
      y: 0,
      width: this.data.canvasWidth,
      height: this.data.canvasHeight,
      destWidth: this.data.canvasdestWidth,
      destHeight: this.data.canvasdestHeight,
      success: res => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: res => {
            // console.log(this.saveTempFilePath)
            wx.showModal({
              title: "保存成功！",
              content: "图片已保存到本地相册",
              showCancel: false,
              success(res) {

              }
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
    setTimeout(() => {
      wx.hideLoading()
    }, 1000)


  },


  //V3.0 获取手机号码
  getPhoneNumber: function (e) {
    var that = this
    if (e.detail.errMsg == "getPhoneNumber:ok") { //允许
      that.decryptPhone(e);
    } else { //拒绝
      wx.showToast({
        title: "请授权！！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    }
  },


  //V3.0 解密手机号码
  decryptPhone: function (e) {

    wx.showLoading({
      title: '解析中...',
      mask: true
    })

    var that = this;
    let code = that.data.code;
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;

    wx.request({
      url: app.globalData.base_url + 'resource/getWXPhoneDirect',
      data: {
        iv: iv,
        js_code: code,
        encrypted: encryptedData,
        tuiJianRenId: that.data.tjr_id,
        dianPuId: that.data.dianPuId
      },
      success: function (res) {
        // console.log("解密手机号码:" + JSON.stringify(res.data))

        if (res.data.purePhoneNumber == '' || res.data.status == 500) {

          wx.showToast({
            title: '解析异常，右上角重新进入小程序', // 提示的内容
            icon: "none", // 图标，默认success
            duration: 3000, // 提示的延迟时间，默认1500
            mask: false, // 是否显示透明蒙层，防止触摸穿透
          })

        } else {
          wx.setStorageSync(app.globalData.OPENID, res.data.openId)
          wx.setStorageSync(app.globalData.PERSON_ID, res.data.personId)
          wx.setStorageSync(app.globalData.TOKEN, res.data.token)
          wx.setStorageSync(app.globalData.PHONENUMBER, res.data.purePhoneNumber)
          wx.setStorageSync(app.globalData.LOGINSTATUS, true)
          wx.setStorageSync(app.globalData.NiCheng, res.data.niCheng)
          wx.setStorageSync(app.globalData.TouXiang, res.data.touXiangUrl)


          that.setData({
            personId: res.data.personId,
            IsLogin: true,
            touXiangUrl: res.data.touXiangUrl,
            niCheng: res.data.niCheng,
            phone: res.data.purePhoneNumber
          })

          // 不是扫码进来的，需要获取我的健康档案list
          if (that.data.guid_short == 0) {
            that.getToken_YJY()
          }

        }

        if (that.data.selectIndex == 1) {
          that.setData({
            shareble: true,
            bottomViewble: true,
          })
        }

        if (that.data.selectIndex == 2) {
          that.gouMaibind()
        }

        if (that.data.selectIndex == 3) {
          that.addshopcar()
        }
      },
      fail: function (err) {
        that.setData({
          IsLogin: false
        })
        wx.showToast({
          title: '获取数据失败,请检查网络', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      },
      complete: function (res) {
        wx.hideLoading();
      }
    })
  },


  //登录同步健康数据
  // syncData(token) {

  //   wx.request({
  //     url: app.globalData.base_url + 'qiTa/tongBuJiuZhenRenAndGouMaiChanPin',
  //     header: {
  //       'token': token,
  //     },
  //     success: function (res) {
  //       console.log("同步数据成功")
  //     },
  //     fail: function (err) {
  //       console.log("同步数据失败")
  //     },
  //     complete: function (res) {
  //       console.log("同步数据完成")

  //     }
  //   })


  // },

  //协议
  bindXieyiTap: function () {
    wx.navigateTo({
      url: '/pkg_wo/pages/xieyiInfo/xieyiInfo',
    })

  },

  //赠品类别
  Typeswitch: function (e) {
    var that = this

    if (that.data.zs_productId == e.currentTarget.dataset.id) {
      wx.showToast({
        title: '您已取消赠品', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
      that.setData({
        zs_productId: 0,
      })

    } else {
      that.setData({
        zs_productId: e.currentTarget.dataset.id,
      })
    }

  },


  //跳转医师详情
  doctortap: function (e) {
    var ysid = e.currentTarget.dataset.id;
    console.log(ysid)
    wx.navigateTo({
      url: '/pkg_doctors/pages/doctor/doctor?ysid=' + ysid,
    })
  },


  //圖片滑动监控
  scrolltolower: function () {
    this.setData({
      scrollFlag: true
    })
  },

  scrolltoupper: function () {
    this.setData({
      scrollFlag: false
    })
  },


  //众筹
  bindToRaise: function () {
    if (this.data.IsLogin) {
      this.setData({
        raiseble: true,
        bottomViewble: true,
      })
    } else {
      wx.showToast({
        title: '请先登录', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })

    }
  },


  //发起众筹
  bindToRaiseStart: function () {


    if ((this.data.guid == 0 || this.data.guid == '')) {

      wx.showToast({
        title: "服务包服务对象，不能为空！", // 提示的内容
        icon: "none", // 图标，默认success
        duration: 3000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })

    } else {
      if (this.data.userName !== '' || this.data.provinceName !== '' || this.data.cityName !== '' || this.data.countyName !== '' || this.data.detailInfo !== '' || this.data.telNumber !== '') {

        this.getgenerateZc()
        this.closeGoumai();
      } else {
        wx.showToast({
          title: "收货地址不能为空！", // 提示的内容
          icon: "none", // 图标，默认success
          duration: 3000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      }
    }

  },


  //生成众筹
  getgenerateZc: function () {
    var that = this
    let data = {
      chanPinId: that.data.productId,
      chanPinLeiXing: 2,
      patientUniqueGuid: that.data.guid,
      fenShu: that.data.goumaiCount,
      dianPuId: that.data.dianPuId,
      wxUserName: that.data.userName,
      wxPostalCode: that.data.postalCode,
      wxProvinceName: that.data.provinceName,
      wxCityName: that.data.cityName,
      wxCountyName: that.data.countyName,
      wxDetailInfo: that.data.detailInfo,
      wxNationalCode: that.data.nationalCode,
      wxTelNumber: that.data.telNumber
    }
    // console.log(data)
    request.get('zhongChou/addOneZhongChou', data, res => {
      wx.hideLoading();
      // console.log("众筹订单id:" + JSON.stringify(res))
      if (res.statusCode == 200) {
        wx.navigateTo({
          url: '/pages/raiseInfo/raiseInfo?zhongChouOrderFormId=' + res.data.zhongChouOrderFormId
        })

      } else {
        wx.showToast({
          title: '众筹发起失败', // 提示的内容
          icon: "none", // 图标，默认success
          duration: 1000, // 提示的延迟时间，默认1500
          mask: false, // 是否显示透明蒙层，防止触摸穿透
        })
      }
    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '生成失败！', // 提示的内容
        icon: "none", // 图标，默认success
        duration: 1000, // 提示的延迟时间，默认1500
        mask: false, // 是否显示透明蒙层，防止触摸穿透
      })
    })

  },
  //选择地址
  setAderssTap: function () {
    var that = this
    if (wx.chooseAddress) {
      wx.chooseAddress({
        success: function (res) {
          wx.setStorageSync(app.globalData.USERNAME, res.userName);
          wx.setStorageSync(app.globalData.PROVINCENAME, res.provinceName);
          wx.setStorageSync(app.globalData.CITYNAME, res.cityName);
          wx.setStorageSync(app.globalData.COUNTYNAME, res.countyName);
          wx.setStorageSync(app.globalData.DETAILINFO, res.detailInfo);
          wx.setStorageSync(app.globalData.TELNUMBER, res.telNumber);
          wx.setStorageSync(app.globalData.NATIONALCODE, res.nationalCode);
          wx.setStorageSync(app.globalData.POSTALCODE, res.postalCode);
          that.setData({
            userName: res.userName,
            provinceName: res.provinceName,
            cityName: res.cityName,
            countyName: res.countyName,
            detailInfo: res.detailInfo,
            telNumber: res.telNumber,
            nationalCode: res.nationalCode,
            postalCode: res.postalCode,
          })
        },
        fail: function () {


          wx.openSetting({
            success: (res) => {
              if (res.authSetting["scope.address"]) { ////如果用户重新同意了授权
                wx.chooseAddress({
                  success: function (ress) {
                    wx.setStorageSync(app.globalData.USERNAME, ress.userName);
                    wx.setStorageSync(app.globalData.PROVINCENAME, ress.provinceName);
                    wx.setStorageSync(app.globalData.CITYNAME, ress.cityName);
                    wx.setStorageSync(app.globalData.COUNTYNAME, ress.countyName);
                    wx.setStorageSync(app.globalData.DETAILINFO, ress.detailInfo);
                    wx.setStorageSync(app.globalData.TELNUMBER, ress.telNumber);
                    wx.setStorageSync(app.globalData.NATIONALCODE, ress.nationalCode);
                    wx.setStorageSync(app.globalData.POSTALCODE, ress.postalCode);
                    that.setData({
                      userName: ress.userName,
                      provinceName: ress.provinceName,
                      cityName: ress.cityName,
                      countyName: ress.countyName,
                      detailInfo: ress.detailInfo,
                      telNumber: ress.telNumber,
                      nationalCode: ress.nationalCode,
                      postalCode: ress.postalCode,
                    })

                  },
                })
              }
            }
          })
        }
      })
    } else {
      console.log('当前微信版本不支持chooseAddress');
    }
    // wx.chooseInvoiceTitle({
    //     success(res) {
    //          console.log("发票:"+JSON.stringify(res))
    //     }
    // })
  },

  //添加姓名
  bindNameInput: function (e) {
    this.setData({
      jzrname: e.detail.value
    })
  },


  //添加就诊人手机号
  bindPhoneInput: function (e) {
    this.setData({
      jzrphone: e.detail.value
    })
  },

  //添加身份证号码
  bindsfzInput: function (e) {
    this.setData({
      jzrsfz: e.detail.value
    })
  },



})